//
//  SecViewController.m
//  BGM
//
//  Created by liuqin on 2018/11/25.
//  Copyright © 2018年 com.alirtc.demo. All rights reserved.
//

#import "MessageViewController.h"
#import "Common.h"
#import "MeTableViewCell.h"
#import "CommonView.h"
#import <NIMSDK/NIMSDK.h>
#import "BGMUser.h"
#import "BGMHTTP.h"
#import "MessageTableViewCell.h"
#import "ChatViewController.h"
#import "MessageListViewController.h"
#import "BaseTabBarViewController.h"
@interface MessageViewController ()<
UITableViewDataSource,UITableViewDelegate,
NIMChatManagerDelegate
>


@property (nonatomic, strong)NSMutableArray *allFriends;
@property (nonatomic, strong)NSMutableArray *allGroups;

@property (nonatomic, strong)UITableView *mesTableView;


@property (nonatomic, strong)NSString *systems;//系统消息
@property (nonatomic, strong)NSString *helps;//帮忙消息
@property (nonatomic, strong)NSString *acknowledges;//答谢消息

@end

@implementation MessageViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
//    [self performSelector:@selector(reloadMessegTable) withObject:nil afterDelay:5];
//    NIMDeleteMessagesOption *option = [[NIMDeleteMessagesOption alloc] init];
//    option.removeSession = YES;
//    option.removeTable  = YES;
//    [[NIMSDK sharedSDK].conversationManager deleteAllMessages:option];


    [self reloadMessegTable];
}
- (void)reloadMessegTable{
    
    NSArray *allSession = [NIMSDK sharedSDK].conversationManager.allRecentSessions;
    self.allFriends = [[NSMutableArray alloc]init];
    self.allGroups = [[NSMutableArray alloc]init];
    for (NIMRecentSession *recentSeesion in allSession) {
        if (recentSeesion.session.sessionType == NIMSessionTypeP2P) {
            [self.allFriends addObject:recentSeesion];
        }else if(recentSeesion.session.sessionType == NIMSessionTypeTeam){
            [self.allGroups addObject:recentSeesion];
        }
    }
    [self getMessageState];
    [self.mesTableView reloadData];
//    NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:1];
//    [self.mesTableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
//
//    indexSet=[[NSIndexSet alloc]initWithIndex:2];
//    [self.mesTableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navview.hidden = NO;
    self.titleLabel.hidden = NO;
    self.titleLabel.text = @"消息";
    
 
    
    self.mesTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.navview.frame.size.height, SCREENW, SCREENH-self.navview.frame.size.height-(SCREENH>736?90:50))];
    self.mesTableView.backgroundColor = [UIColor clearColor];
    self.mesTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.mesTableView.delegate = self;
    self.mesTableView.dataSource = self;
    [self.view addSubview:self.mesTableView];
    
    [[[NIMSDK sharedSDK]chatManager]addDelegate:self];
   

}

- (void)getMessageState{
    
    NSDictionary *param = @{@"userToken":[BGMUser shareInstance].userToken,@"userId":[BGMUser shareInstance].userId};
    
    [BGMHTTP requestWithMethodName:@"message/getMessageUnreadSize" parameters:param completion:^(BOOL success, NSError *error, NSDictionary *result) {
        NSDictionary *date = [result objectForKey:@"data"];
        dispatch_async(dispatch_get_main_queue(), ^{
            self.systems = [NSString stringWithFormat:@"%@",[date objectForKey:@"systems"]];
            self.helps = [NSString stringWithFormat:@"%@",[date objectForKey:@"helps"]];
            self.acknowledges = [NSString stringWithFormat:@"%@",[date objectForKey:@"acknowledges"]];
            NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:0];
            [self.mesTableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationNone];
            });
    }];
    
}

#pragma mark UITABLEVIEWDELEAGE


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==1) {
       return 30;
    }else{
        return 0;
    }
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section ==0) {
        return NO;
    }
    return YES;
    
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
}
- (NSArray *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewRowAction *action0 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"删除" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        
        if (indexPath.section ==1) {
            NIMRecentSession *session = [self.allGroups objectAtIndex:indexPath.row];
            [self.allGroups removeObjectAtIndex:indexPath.row];

            [self deleCellSession:session];
            
        }else if (indexPath.section ==2){
            NIMRecentSession *session = [self.allFriends objectAtIndex:indexPath.row];
            [self.allFriends removeObjectAtIndex:indexPath.row];
            [self deleCellSession:session];
            
        }
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
 
    }];
    action0.backgroundColor = bgmyelloeColor;

    UITableViewRowAction *action1 = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"置顶" handler:^(UITableViewRowAction *action, NSIndexPath *indexPath) {
        NSLog(@"点击了置顶");
        // 收回左滑出现的按钮(退出编辑模式)
        tableView.editing = NO;
    }];
    
  
    return @[action0, action1];
}



- (void)deleCellSession:(NIMRecentSession *)recentSession{
//    NIMSession  *session = recentSession.session;
    [[[NIMSDK sharedSDK]conversationManager] deleteRecentSession:recentSession];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section==0) {
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 0, 0)];
        return label;
    }else if(section == 1){
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 30)];
        label.backgroundColor = [UIColor whiteColor];
        label.text = @"     消息";
        label.textColor = bgmmainColor;
        label.font = [UIFont systemFontOfSize:13];
        return label;
    }else{
        UIView *view = [[UIView alloc]init];
        return view;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section ==0) {
        return 3;
    }else if(section == 1){
        return self.allGroups.count;
    }else{
        return self.allFriends.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section==0) {
         return 50;
    }else {
        return 70;
    }
   
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section == 0){
        static NSString *identifier = @"MeTableViewCell";
        MeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell ==nil) {
            cell = [[MeTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.rightBtn.hidden = NO;
            cell.rightLabel.hidden = NO;
            cell.rightLabel.backgroundColor = bgmyelloeColor;
            cell.rightLabel.frame = CGRectMake(SCREENW-60, 20, 10, 10);
            cell.rightLabel.layer.masksToBounds = YES;
            cell.rightLabel.layer.cornerRadius = 5;
        }
        [cell.iconBtn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"message_%d",(int)indexPath.row]] forState:UIControlStateNormal];
        if (indexPath.row==0) {
            cell.contentLabel.text = @"帮忙消息";
            if([self.helps isEqualToString:@"no"]){
                cell.rightLabel.hidden = YES;

            }else{
                cell.rightLabel.hidden = NO;
            }
        }else if(indexPath.row==1){
            cell.contentLabel.text = @"系统通知";
            if([self.systems isEqualToString:@"no"]){
                cell.rightLabel.hidden = YES;
            }else{
                cell.rightLabel.hidden = NO;
            }
        }else if(indexPath.row==2){
            cell.contentLabel.text = @"答谢通知";
            
            if([self.acknowledges isEqualToString:@"no"]){
                cell.rightLabel.hidden = YES;
                
            }else{
                cell.rightLabel.hidden = NO;
            }
        }
        return cell;
        
    }
    else{
        static NSString *identifier = @"MessageTableViewCell";
        MessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (cell ==nil) {
            cell = [[MessageTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        }
        if (indexPath.section ==1) {
            id msg = [self.allGroups objectAtIndex:indexPath.row];
            if ([msg isKindOfClass:[NIMMessage class]]) {
                [cell setTeamMessageInfo:msg];
            }else{
                NIMRecentSession *session = msg;
                NIMMessage *message = session.lastMessage;
                [cell setTeamMessageInfo:message];
                int unreadCount = (int)session.unreadCount;
                if(unreadCount>0){
                     cell.readStatus.hidden = NO;
                }else{
                    cell.readStatus.hidden = YES;
                }
            }
        }else{
            id msg = [self.allFriends objectAtIndex:indexPath.row];
            if ([msg isKindOfClass:[NIMMessage class]]) {
                [cell contentSession:msg];
            }else{
                NIMRecentSession *session = msg;
                NIMMessage *message = session.lastMessage;
                [cell contentSession:message];
                int unreadCount = (int)session.unreadCount;
                if(unreadCount>0){
                    cell.readStatus.hidden = NO;
                }else{
                    cell.readStatus.hidden = YES;
                }

            }
        }
      
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section ==0) {
        MessageListViewController *vc = [[MessageListViewController alloc]init];
         vc.maeesgeType = (int)indexPath.row+1;
        [self.navigationController pushViewController:vc animated:YES];
    }
    else if (indexPath.section ==1){
        NIMRecentSession *RecentSession = [self.allGroups objectAtIndex:indexPath.row];
        NSString *otherid  = RecentSession.session.sessionId;
        NIMTeam *team = [[[NIMSDK sharedSDK]teamManager] teamById:otherid];
        ChatViewController *vc = [[ChatViewController alloc]init];
         vc.otherName = team.teamName;
        vc.OtherId = team.teamId;
        vc.isGroup = YES;
        vc.groupId =team.teamId;
        vc.groupMessage = team.serverCustomInfo;
        vc.historysession =RecentSession.session;
        [self.navigationController pushViewController:vc animated:YES];
        
        NIMSession *session = RecentSession.session;
        [[NIMSDK sharedSDK].conversationManager markAllMessagesReadInSession:session];
    }
    else{
        
        NIMRecentSession *RecentSession = [self.allFriends objectAtIndex:indexPath.row];
        NSString *otherid  = RecentSession.session.sessionId;
        NIMUser *user = [[NIMSDK sharedSDK].userManager userInfo:otherid];
        ChatViewController *vc = [[ChatViewController alloc]init];
        vc.otherName = user.userInfo.nickName;
        vc.OtherId = otherid;//会话ID,如果当前session为team,则sessionId为teamId,如果是P2P则为对方帐号
        vc.otherImage =user.userInfo.avatarUrl;
        vc.historysession =RecentSession.session;
        [self.navigationController pushViewController:vc animated:YES];
        
        NIMSession *session = RecentSession.session;
        [[NIMSDK sharedSDK].conversationManager markAllMessagesReadInSession:session];
     }
    
}

-(void)onRecvMessages:(NSArray<NIMMessage *> *)messages{

    for (NIMMessage *message in messages) {
        NIMSession *session = message.session;
        if (session.sessionType == NIMSessionTypeP2P) { //一对一
            NIMSession *session = message.session;
            BOOL b = NO;
            for (int i = 0; i<self.allFriends.count; i++) {
                NIMRecentSession *Recentsession = [self.allFriends objectAtIndex:i];
                 NSString *otherid  = Recentsession.session.sessionId;
                if ([otherid isEqualToString:session.sessionId]) {
                   NIMRecentSession *new = [[NIMSDK sharedSDK].conversationManager recentSessionBySession:session];
                    [self.allFriends replaceObjectAtIndex:i withObject:new];
                    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:i inSection:2];
                    [self.mesTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
                    b = YES;
                    break;
                }
            }
            
            if (!b) {
                 NIMRecentSession *new = [[NIMSDK sharedSDK].conversationManager recentSessionBySession:session];
                [self.allFriends addObject:new];
                [self.mesTableView reloadData];
//                [self.mesTableView beginUpdates];
//                 NSIndexPath *indexPath=[NSIndexPath indexPathForRow:self.allFriends.count-1 inSection:2];
//                [self.mesTableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
//                [self.mesTableView endUpdates];
            }
        }else if (session.sessionType == NIMSessionTypeTeam){  //群组
            
            BOOL b = NO;
            for (int i = 0; i<self.allGroups.count; i++) {
                NIMRecentSession *Recentsession = [self.allGroups objectAtIndex:i];
                NSString *otherid  = Recentsession.session.sessionId;
                if ([otherid isEqualToString:session.sessionId]) {
                    NIMRecentSession *new = [[NIMSDK sharedSDK].conversationManager recentSessionBySession:session];
                    [self.allGroups replaceObjectAtIndex:i withObject:new];
                    
                    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:i inSection:1];
                    [self.mesTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
                    b = YES;
                    break;
                }
            }
            
            if (!b) {
                
                NIMRecentSession *new = [[NIMSDK sharedSDK].conversationManager recentSessionBySession:session];
                [self.allGroups addObject:new];
                [self.mesTableView reloadData];
                
//                [self.mesTableView beginUpdates];
//                NSIndexPath *indexPath=[NSIndexPath indexPathForRow:self.allFriends.count-1 inSection:2];
//                [self.mesTableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
//                [self.mesTableView endUpdates];
            }
            
        }
    }
    
//    [self tabbarItemAddCircle];
    
}

- (void)tabbarItemAddCircle{
    
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    BaseTabBarViewController *tabBar = (BaseTabBarViewController *)window.rootViewController;
    [tabBar showBadgeWithIndex:1];
}



- (UIViewController *)getCurrentVC

{
    
    UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
    UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
    return currentVC;
    
}

- (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC

{
    
    UIViewController *currentVC;
    if ([rootVC presentedViewController]) {
        rootVC = [rootVC presentedViewController];
    }
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
    } else if ([rootVC isKindOfClass:[UINavigationController class]]){
        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
    } else {
        currentVC = rootVC;
    }
    return currentVC;
    
}




-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
